package com.atguigu.gulimall.ssoclient.controller;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * description: HelloController
 * date: 2022/12/13 20:37
 * author: MR.孙
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String SSOServerUrl;


    /**
     * 无需登录即可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }




    /**
     * 需要认证才能访问
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/employees")
    public String employees(@RequestParam(value="token", required = false) String token,
                            Model model,
                            HttpSession session){

        if (StringUtils.isNotEmpty(token)) {
            //TODO 去认证中心查询用户的信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = entity.getBody();
            session.setAttribute("loginUser", body);
        }

        Object user = session.getAttribute("loginUser");
        if (user==null) {
            //带上redirect_ur=??? 是因为跳转打开单点服务器登录成功后要知道需要返回什么页面
            return "redirect:" + SSOServerUrl + "?redirect_url=http://client1.com:8081/employees";//没有认证需要去认证
        }else {
            ArrayList<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            emps.add("王五");
            model.addAttribute("emps", emps);
            return "list";
        }

    }




}
